package com.handong.handserialprogram.module.serialport;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.constants.HttpConstant;
import com.handong.handserialprogram.model.bean.ChildTagGroupModel;
import com.handong.handserialprogram.model.bean.TagCoordinateModel;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.model.status.FootRingStatus;
import com.handong.handserialprogram.model.status.RingResponse;
import com.handong.handserialprogram.thread.EmergencyRunnable;
import com.handong.handserialprogram.thread.FinMissRunnable;
import com.handong.handserialprogram.thread.ReadNewRunnable;
import com.handong.handserialprogram.thread.SendRunnable;
import com.handong.handserialprogram.thread.UploadRunnable;
import com.handong.handserialprogram.threadpool.WorkExecutePool;
import com.handong.handserialprogram.utils.CheckUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.ObjectToByteArray;
import com.handong.handserialprogram.utils.SPUtil;
import com.handong.handserialprogram.voice.VoiceImpl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.pda.serialport.SerialPort;
import cn.pda.serialport.Tools;

/**
 * 串口模块。
 * <p>
 * Created by Administrator on 2016/12/14.
 */

public class SerialPortUtil {

    private static final String TAG = SerialPortUtil.class.getSimpleName();

    private static final int BAUD_RATE = 115200;
    private static final int PORT = 13;
    //public byte order=0;
    //public static boolean TEST_DEBUG = false;

    private Context mAppContext;
    private static SerialPortUtil mSerialPortUtil;
    public List<String> mBindedRingList = new ArrayList<>();

    private Object mLock = new Object();
    private byte mOrderSequence = 0;

    private SerialPort mSerialPort;
    private OutputStream mWriteStream;
    private InputStream mReadStream;

    public CopyOnWriteArrayList<FootRingNewEntity> mRingList;
    private UploadRunnable mUploadRunnable;
    private TagCoordinateModel mUploadModel;
    private FinMissRunnable mFinMissRunnable;
    public ReadNewRunnable mReadRunnable;
    //private SendRunnable mSendRunnable;
    //private String missionId;

    private Handler mConnectRemind;

    private ExecutorService mWorkPool;
    public String currentCode = "";
    public SendRunnable mSendRunnable;

    public CopyOnWriteArrayList<FootRingNewEntity> getRingList() {
        return mRingList;
    }

    public void setRingList(CopyOnWriteArrayList<FootRingNewEntity> ringList) {
        mRingList = ringList;
        if (mReadRunnable != null) {
            mReadRunnable.setEntityList(ringList);
        }
    }


    private SerialPortUtil(Context context) {
        mAppContext = context.getApplicationContext();
        mRingList = new CopyOnWriteArrayList<>();
        mSerialPort = new SerialPort();
    }

    public void SetReadRunnableIsStop(Boolean isStop) {
        mReadRunnable.isStopRecycle = isStop;
    }

//    public void ReadData ()
//    {
//        mReadRunnable.DoWork();
//    }

    public static SerialPortUtil getInstance(Context context) {
        if (mSerialPortUtil == null) {
            synchronized (SerialPortUtil.class) {
                if (mSerialPortUtil == null) {
                    mSerialPortUtil = new SerialPortUtil(context);
                    JLog.d(TAG, "SerialPort inited.");
                }
            }
        }
        return mSerialPortUtil;
    }

    /**
     * 是否开启报警提示。
     *
     * @param isPlaySound
     */
    public void setPlaySound(boolean isPlaySound) {
        mReadRunnable.setPlayWarningVoice(isPlaySound);
    }

    /**
     * 添加声音
     *
     * @param res
     */
    public void addSound(int res) {
        mReadRunnable.addSound(res);
    }

    public String getSequence() {
        if (this.mOrderSequence == 100) {
            this.mOrderSequence = 0;
        }
        mOrderSequence++;
        String str2 = Integer.toHexString(this.mOrderSequence).toUpperCase();
        if (this.mOrderSequence < 16) {
            str2 = "0" + str2;
        }
        return str2;
    }

    public byte[] getSendStrByFootRingEntity(FootRingNewEntity entity) {
        //头
        StringBuilder result = new StringBuilder("6864");

        //协议版本号
        result.append("21");

        //脚环id
        if (entity.getRingID() == null) {
            result.append("0000");
        } else {
            result.append(entity.getRingID());
        }

        //手持机id
        result.append(SPUtil.getStringValue(SPUtil.IMEI_CRC));
        //功能码
        result.append("00");
        //数据域长度
        result.append(Tools.intToHexString(76));
        Log.d("手持机发送数据","到长度："+result);
        //设定距离，当前小数部分为0
        result.append(Tools.intToHexString(entity.getSetRingDistance()));
        //报警相关
        int voice = 0;
        if (entity.isLockAlarm()) {
            voice += 2;
        }

        if (entity.isStopAlarm()) {
            voice += 1;
        }

        result.append(Tools.intToHexString(voice));

        int task = 0;
        if (entity.isRingUpdate()){
            task +=128 ;
        }
        if (entity.isLoginOutAlarm()) { //注销
            task += 32;
        }

        if (entity.isWork()) {  //激活
            task += 16;
        }
        if (entity.isNormalWork()) { //查找设备
            task += 8;
        }

        if (entity.isWithdraw()) {  //撤防
            task += 1;

        }

        //task
        result.append(Tools.intToHexString(task));

        Log.d("手持机发送数据","距离、报警、task"+result);
        //语音类别
        int jh_data = SPUtil.getIntValue(SPUtil.JH_VOICE);
        result.append(Integer.toHexString((int)Math.ceil(SPUtil.getIntValue(SPUtil.JH_VOICE) * 15 / 100f)));
        if (SPUtil.getBooleanValue(SPUtil.JH_OPEN)) {
            result.append(Integer.toHexString(1));
        } else {
            result.append(Integer.toHexString(0));
        }

        int bj_data1 = (int)Math.ceil(SPUtil.getIntValue(SPUtil.BJ_VOICE) * 15 / 100f);
        result.append(Integer.toHexString(bj_data1));

        int bj_data2 = SPUtil.getIntValue(SPUtil.BJ_NUM);
        result.append(Integer.toHexString(bj_data2));

        int ts_data1 = (int)Math.ceil(SPUtil.getIntValue(SPUtil.TS_VOICE) * 15 / 100f);
        result.append(Integer.toHexString(ts_data1));

        int ts_data2 = SPUtil.getIntValue(SPUtil.TS_NUM);
        result.append(Integer.toHexString(ts_data2));

        Log.d("手持机发送数据","jh_data"+jh_data+"boolean:"+SPUtil.getBooleanValue(SPUtil.JH_OPEN)+"bj_data"+bj_data1+"ts_data"+ts_data1);
        Log.d("手持机发送数据","加音量："+result);
        // 设备数量
        result.append(Tools.intToHexString(SPUtil.getIntValue(SPUtil.FOOT_RING_NUMBER)));
        Log.d("手持机发送数据：","脚环数量："+Integer.toHexString(SPUtil.getIntValue(SPUtil.FOOT_RING_NUMBER))+"数量："+(SPUtil.getIntValue(SPUtil.FOOT_RING_NUMBER)));
        //ip+端口
        String ip = SPUtil.getStringValue(SPUtil.FOOTRING_SERVER_IP);
        int port = SPUtil.getIntValue(SPUtil.FOOT_PORT);
        String[] ipArr = ip.split("\\.");
        for (String ipString :
                ipArr) {
            result.append(Tools.intToHexString(Integer.parseInt(ipString)));
        }
        result.append(Tools.intToHexString(port, 4));
        Log.d("手持机发送数据：","IP："+ip+"  port: "+Tools.intToHexString(port, 4));
//
//        if(SPUtil.getBooleanValue(SPUtil.OPEN_GD_GPS)){
//            result.append(Tools.intToHexString(1));
//        }else {
//            result.append(Tools.intToHexString(2));
//        }

//        String st1 = SPUtil.getStringValue(SPUtil.FOOT_RING_APN_1);
//        String st2 = SPUtil.getStringValue(SPUtil.FOOT_RING_APN_2);
//        String st3 = SPUtil.getStringValue(SPUtil.FOOT_RING_APN_3);
//        result.append(pushString(Tools.str2HexStr(st1),40));
//        result.append(pushString(Tools.str2HexStr(st2),40));
//        result.append(pushString(Tools.str2HexStr(st3),20));
        byte[] resultStr = CheckUtil.checkSum8Caculation(result.toString());
        //result+=entity.getActualRingDistance();
        return resultStr;
    }
    public byte[] getSendStrByFootRingEntity1(String ringId) {
        //头
        StringBuilder result = new StringBuilder("6864");
        //协议版本号
        result.append("21");
        //脚环id
         result.append(ringId);

        //手持机id
        result.append(SPUtil.getStringValue(SPUtil.IMEI_CRC));
        //功能码
        result.append("00");
        //数据域长度
        result.append(Tools.intToHexString(13));

        //设定距离，当前小数部分为0
        result.append(Tools.intToHexString(8));
        //报警相关
        int voice = 0;
        result.append(Tools.intToHexString(voice));

        int task = 0;

        task += 32;

        //task
        result.append(Tools.intToHexString(task));
        //语音类别
        int jh_data = SPUtil.getIntValue(SPUtil.JH_VOICE);
        result.append(Integer.toHexString(jh_data));
        if (SPUtil.getBooleanValue(SPUtil.JH_OPEN)) {
            result.append(Integer.toHexString(1));
        } else {
            result.append(Integer.toHexString(0));
        }

        int bj_data1 = 15;
        result.append(Integer.toHexString(bj_data1));

        int bj_data2 = SPUtil.getIntValue(SPUtil.BJ_NUM);
        result.append(Integer.toHexString(bj_data2));

        int ts_data1 = 15;
        result.append(Integer.toHexString(ts_data1));

        int ts_data2 = SPUtil.getIntValue(SPUtil.TS_NUM);
        result.append(Integer.toHexString(ts_data2));



        // 设备数量
        result.append(Tools.intToHexString(SPUtil.getIntValue(SPUtil.FOOT_RING_NUMBER)));
        Log.d("脚环数据：","脚环数量："+Integer.toHexString(SPUtil.getIntValue(SPUtil.FOOT_RING_NUMBER))+"数量："+(SPUtil.getIntValue(SPUtil.FOOT_RING_NUMBER)));
        //ip+端口
        String ip = SPUtil.getStringValue(SPUtil.FOOTRING_SERVER_IP);
        int port = SPUtil.getIntValue(SPUtil.FOOT_PORT);
        String[] ipArr = ip.split("\\.");
        for (String ipString :
                ipArr) {
            result.append(Tools.intToHexString(Integer.parseInt(ipString)));
        }
        result.append(Tools.intToHexString(port, 4));



        byte[] resultStr = CheckUtil.checkSum8Caculation(result.toString());
        //result+=entity.getActualRingDistance();
        return resultStr;
    }

    //补充位数
    private String pushString(String str, int i) {
        StringBuilder result = new StringBuilder(str);
        if (str.length() != i) {
            for (int j = str.length(); j < i; j++) {
                result.append(0);
            }
        }
        return String.valueOf(result);
    }
    /**
     * 读取串口数据
     */
    public void openSerialPortToReadData() {
        if (mReadStream != null || mWriteStream != null) {
            return;
        }
      /*  if (TEST_DEBUG) {
           // onTest();
           // open(0);
        } else {*/
        //扫描脚环，添加其他信息
        open();
        //}
    }

    /**
     * 开始读取串口数据
     */
    private void open() {
        try {
            //mSerialPort.closeSerial(PORT);
            mSerialPort.rfid_poweron();

            this.mSerialPort.openSerial(PORT, BAUD_RATE);
            Log.d("脚环数据","端口打开");
            if ((this.mReadStream == null) || (this.mWriteStream == null)) {
                this.mReadStream = this.mSerialPort.getInputStream();
                this.mWriteStream = this.mSerialPort.getOutputStream();
            }
            if (mWorkPool == null) {
                mWorkPool = Executors.newFixedThreadPool(3);
            }
            if (mReadRunnable == null) {
                boolean isPlayVoice = SPUtil.getBooleanValue(SPUtil.RING_STATUS);
                mReadRunnable = new ReadNewRunnable(this, mReadStream, mRingList, mAppContext, isPlayVoice);
//                mReadRunnable.setOnSendDataListener(new CallBackUtil.OnSendDataListener() {
//                    @Override
//                    public void onSend(FootRingNewEntity entity) {
//                        if (entity!=null&&mWriteStream!=null)
//                        {
//                            try {
//                                mWriteStream.write(getSendStrByFootRingEntity(entity));
//                            }
//                            catch (IOException e) {
//                                e.printStackTrace();
//                            }
//                        }
//
//                    }
//                });
            }
            mWorkPool.execute(mReadRunnable);

        } catch (IOException localIOException) {
            localIOException.printStackTrace();
            JLog.d(TAG, "Serial port open fail.");
        }
    }

    /**
     * 开始发送线程
     */
    public void setSendStart() {
        //打开发送线程
        if (mSendRunnable == null) {
            try {
                mSendRunnable = new SendRunnable(this, mAppContext, mReadRunnable);
                //mSendRunnable.isRunning=true;
                //mSendRunnable.work();

                mWorkPool.execute(mSendRunnable);
            } catch (Exception e) {
                Log.d(TAG, "setSendStart: " + e.getMessage());
            }
        }

    }

    /**
     * 设置上传线程为暂停
     *
     * @param isPause
     */
    public void setIsUploadPause(boolean isPause) {
        if (mSendRunnable != null) {
            mSendRunnable.isPause = isPause;
        }
    }

    /**
     * 开启上传线程
     */
    public void openUploadThread() {
        if (null != mUploadRunnable) {
            return;
        }
        if (this.mUploadRunnable == null) {
            mConnectRemind = new Handler(Looper.getMainLooper());
            this.mUploadRunnable = new UploadRunnable(this, this.mLock, mConnectRemind, mAppContext);
        }
        mWorkPool.execute(mUploadRunnable);
        mReadRunnable.setUploadLocation(true);
        mReadRunnable.isFirst = true;
        //missionId=mId;
    }

    /**
     * 停止上传坐标信息。
     */
    public void closeUploadData() {
        if (mUploadRunnable == null) {
            return;
        }
        SPUtil.remove(SPUtil.MISSION_ID);
        mUploadRunnable.destroy();
        mUploadRunnable = null;
    }


    /**
     * TEST_DEBUG
     */
    private void open(int paramInt) {
        if (mWorkPool == null) {
            mWorkPool = Executors.newFixedThreadPool(2);
        }
        if (mReadRunnable == null) {
            boolean isPlayVoice = SPUtil.getBooleanValue(SPUtil.RING_STATUS);
            mReadRunnable = new ReadNewRunnable(this, mReadStream, mRingList, mAppContext, isPlayVoice);
        }
        mWorkPool.execute(mReadRunnable);
    }

    /**
     * 发送手持机IMEI,只有当该任务包含激活脚环时发送
     */
    public void sendIMEI() {
        if (this.mWriteStream == null) {
            return;
        }
        if (mBindedRingList.isEmpty()) {
            currentCode = "";
            return;
        }
        FootRingNewEntity entity = new FootRingNewEntity();
        entity.setRingID(mBindedRingList.get(0));
        currentCode = mBindedRingList.get(0);
        //entity.setTaskTime(order);
        entity.setIsActive(32);
//        try {
//            this.mWriteStream.write(getSendStrByFootRingEntity(entity));
//            //order++;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 激活脚环
     */
    public void activateFootRing(String id) {
        if (this.mWriteStream == null) {
            return;
        }
        FootRingNewEntity entity = findEntityFromList(id);
        entity.setActionOrder(RingResponse.ACTIVATE_ORDER);
        //entity.setTaskTime(order);
        entity.setIsActive(32);
        JLog.d(TAG, "脚环:" + id + "激活。");
//        try {
//            this.mWriteStream.write(getSendStrByFootRingEntity(entity));
//            entity.setTaskTime((byte)0);
//        } catch (IOException e) {
//            e.printStackTrace();
//            JLog.d(TAG, "脚环:" + id + "激活失败。");
//        }
    }

    private long SendTime = 0;

    public void sendFootRing(FootRingNewEntity entity) {
        if (this.mWriteStream == null) {
            return;
        }
        byte[] sendData = getSendStrByFootRingEntity(entity);
        Log.d("手持机发送数据", "Send Data:" + Tools.byteToHexString(sendData));
        SendTime++;
        if (SendTime >= 100000L) {
            SendTime = 0;
        }
        Log.d("手持机发送数据", "发送次数" + SendTime   +"长度："+sendData.length);
        try {
            this.mWriteStream.write(sendData);
            entity.setTaskTime((byte) 0);
        } catch (IOException e) {
            e.printStackTrace();
            JLog.d(TAG, "循环发送命令" + Tools.byteToHexString(sendData) + "。");
        }
    }

    public void sendLoginOutFootRing(String ringID) {
        if (this.mWriteStream == null) {
            return;
        }
        byte[] sendData = getSendStrByFootRingEntity1(ringID);
        Log.d("数据传输", "Send Data:" + Tools.byteToHexString(sendData));
        SendTime++;
        if (SendTime >= 100000L) {
            SendTime = 0;
        }
        Log.d("数据传输", "发送次数" + SendTime   +"长度："+sendData.length);
        try {
            this.mWriteStream.write(sendData);
        } catch (IOException e) {
            e.printStackTrace();
            JLog.d("数据传输", "循环发送命令" + Tools.byteToHexString(sendData) + "。");
        }
    }

    /**
     * 设置脚环报警声
     */
    public void setFootRingAlarm(String id, String code) {
//        if (this.mWriteStream == null) {
//            return;
//        }
//        FootRingNewEntity entity = findEntityFromList(id);
//        entity.setActionOrder(RingResponse.ALARM_SOUND_SET);
//        String cmd = "14" + getSequence() + "06" + id + code;
//        JLog.d(TAG, "Send Data:" + cmd);
//        try {
//            this.mWriteStream.write(CheckUtil.checkSum8Caculation(cmd));
//        } catch (IOException e) {
//            e.printStackTrace();
//            JLog.d(TAG, "脚环:" + id + "设置报警声失败。");
//        }
    }

    /**
     * 设置脚环IP
     */
    public void setFootRingIP(String id, String ip) {
//        if (this.mWriteStream == null) {
//            return;
//        }
//        FootRingNewEntity entity = findEntityFromList(id);
//        entity.setActionOrder(RingResponse.SEVER_IP_SET);
//        String cmd = "14" + getSequence() + "F6" + id + ip;
//        JLog.d(TAG, "Send Data:" + cmd);
//        try {
//            this.mWriteStream.write(CheckUtil.checkSum8Caculation(cmd));
//        } catch (IOException e) {
//            e.printStackTrace();
//            JLog.d(TAG, "脚环:" + id + "设置脚环IP失败。");
//        }
    }

    /**
     * 开启配置模式
     */
    public void startConfig(String id) {
//        if (this.mWriteStream == null) {
//            return;
//        }
//        FootRingNewEntity entity = findEntityFromList(id);
//        entity.setActionOrder(RingResponse.PARAMETER_SET);
//        String cmd = "14" + getSequence() + "F9" + id + "00";
//        JLog.d(TAG, "Send Data:" + cmd);
//        try {
//            this.mWriteStream.write(CheckUtil.checkSum8Caculation(cmd));
//        } catch (IOException e) {
//            e.printStackTrace();
//            JLog.d(TAG, "脚环:" + id + "开启配置模式失败。");
//        }
    }

    /**
     * 退出配置模式
     */
    public void endConfig(String id) {
//        if (this.mWriteStream == null) {
//            return;
//        }
//        FootRingNewEntity entity = findEntityFromList(id);
//        entity.setActionOrder(RingResponse.PARAMERT_LOGOUT);
//        String cmd = "14" + getSequence() + "F3" + id + "00";
//        JLog.d(TAG, "Send Data:" + cmd);
//        try {
//            this.mWriteStream.write(CheckUtil.checkSum8Caculation(cmd));
//        } catch (IOException e) {
//            e.printStackTrace();
//            JLog.d(TAG, "脚环:" + id + "退出配置模式失败。");
//        }
    }

    /**
     * 脚环报警。
     */
    public void noiseFootRing(String id) {
        if (this.mWriteStream == null) {
            return;
        }
        FootRingNewEntity entity = findEntityFromList(id);
        if (entity.getStatus() == FootRingStatus.ESCAPE) {
            return;
        }
        entity.setHandAlarm(true);

        JLog.d("SerialPortUtil", "脚环:" + id + "手动报警。");
//        try {
//            this.mWriteStream.write(getSendStrByFootRingEntity(entity));
//        } catch (IOException e) {
//            e.printStackTrace();
//            JLog.d(TAG, "脚环:" + id + "手动报警失败。");
//        }

    }

    public void updateWorking(boolean isWorking) {
        mReadRunnable.isWorking = isWorking;
    }

    /**
     * 修改脚环设定距离。
     *
     * @param distance 新的距离。
     */
    public void updateDistance(String id, String distance) {
        if (this.mWriteStream == null) {
            return;
        }
        FootRingNewEntity entity = findEntityFromList(id);
        entity.setActionOrder(RingResponse.UPDATE_DISTANCE_ORDER);
        int dis = Integer.valueOf(distance, 16);
        entity.setSetRingDistance(dis);
        JLog.d(TAG, "脚环:" + id + "修改设定距离");
//        try {
//            this.mWriteStream.write(getSendStrByFootRingEntity(entity));
//        } catch (IOException e) {
//            e.printStackTrace();
//            JLog.d(TAG, "脚环:" + id + "修改设定距离失败。");
//        }

    }

    /**
     * 授权打开关闭
     */
    public void setLockIsStopAlarm(String id, boolean isStopAlarm) {
        if (this.mWriteStream == null) {
            return;
        }
        FootRingNewEntity entity = findEntityFromList(id);

        entity.setLockAlarm(isStopAlarm);
        if (isStopAlarm) {
            JLog.d(TAG, "脚环:" + id + "停止锁扣报警");
        } else {
            JLog.d(TAG, "脚环:" + id + "开启锁扣报警");
        }

    }

    /**
     * 关闭脚环报警。
     *
     * @param id id。
     */
    public void closeFootRingAlarm(String id) {
        if (this.mWriteStream == null) {
            return;
        }
        FootRingNewEntity entity = findEntityFromList(id);
        entity.setActionOrder(RingResponse.CLOSE_ALARM_RESPONSE);

        entity.setStopAlarm(true);
        JLog.d(TAG, "脚环:" + id + "关闭脚环报警");
//        try {
//            this.mWriteStream.write(getSendStrByFootRingEntity(entity));
//        } catch (IOException e) {
//            e.printStackTrace();
//            JLog.d(TAG, "脚环:" + id + "关闭脚环报警失败。");
//        }
    }

    /**
     * 打开脚环报警。
     *
     * @param id id。
     */
    public void openFootRingAlarm(String id) {
        if (this.mWriteStream == null) {
            return;
        }
        FootRingNewEntity entity = findEntityFromList(id);
        entity.setActionOrder(RingResponse.OPEN_ALARM_RESPONSE);

        entity.setStopAlarm(false);
        JLog.d(TAG, "脚环:" + id + "开启脚环报警");
//        try {
//            this.mWriteStream.write(getSendStrByFootRingEntity(entity));
//        } catch (IOException e) {
//            e.printStackTrace();
//            JLog.d(TAG, "脚环:" + id + "开启脚环报警失败。");
//        }
    }

    /**
     * 来自服务器的消除警报命令。
     *
     * @param id 脚环id。
     */
    public void closeFootRingAlarmFromServer(String id) {
        if (this.mWriteStream == null || mRingList.isEmpty()) {
            return;
        }

        FootRingNewEntity entity = findEntityFromList(id);
//        if (entity.getStatus() == FootRingStatus.ESCAPE) {
//            return;
//        }
        entity.setStopAlarm(true);
        JLog.d(TAG, "脚环:" + id + "关闭脚环报警");
//        try {
//            this.mWriteStream.write(getSendStrByFootRingEntity(entity));
//        } catch (IOException e) {
//            e.printStackTrace();
//            JLog.d(TAG, "脚环:" + id + "关闭脚环报警失败。");
//        }
    }

    /**
     * 来自服务器的开启警报命令。
     *
     * @param id 脚环id。
     */
    public void openFootRingAlarmFromServer(String id) {
        if (this.mWriteStream == null || mRingList.isEmpty()) {
            return;
        }

        FootRingNewEntity entity = findEntityFromList(id);
//        if (entity.getStatus() == FootRingStatus.ESCAPE) {
//            return;
//        }
        entity.setStopAlarm(false);
        JLog.d(TAG, "脚环:" + id + "开启脚环报警");
//        try {
//            this.mWriteStream.write(getSendStrByFootRingEntity(entity));
//        } catch (IOException e) {
//            e.printStackTrace();
//            JLog.d(TAG, "脚环:" + id + "关闭脚环报警失败。");
//        }
    }

    /**
     * 休眠脚环。
     *
     * @param id id。
     */
    public void logoutFootRing(String id) {
       /* if (TEST_DEBUG) {
            FootRingNewEntity entity = findEntityFromList(id);
            entity.setActionOrder(RingResponse.LOGOUT_ORDER);
            return;
        }*/
        if (this.mWriteStream == null) {
            return;
        }
        if (mSendRunnable != null) {
            mSendRunnable.DelayTime = 100;
        }

        FootRingNewEntity entity = findEntityFromList(id);
        entity.setActionOrder(RingResponse.LOGOUT_ORDER);
        entity.setStopMissionReceive(false);
        entity.setStopMissionNoDataCount(0);
        JLog.d(TAG, "脚环" + id + " 休眠");
//        try {
//            this.mWriteStream.write(getSendStrByFootRingEntity(entity));
//        } catch (IOException e) {
//            e.printStackTrace();
//            JLog.d(TAG, "脚环:" + id + "休眠失败。");
//        }
    }


    /**
     * 恢复脚环。
     *
     * @param id id。
     */
    public void resumeFootRing(String id) {
       /* if (TEST_DEBUG) {
            FootRingNewEntity entity = findEntityFromList(id);
            entity.setActionOrder(RingResponse.LOGOUT_ORDER);
            return;
        }*/
        if (this.mWriteStream == null) {
            return;
        }
        if (mSendRunnable != null) {
            mSendRunnable.DelayTime = 30;
        }

        FootRingNewEntity entity = findEntityFromList(id);
        // entity.setActionOrder(RingResponse.LOGOUT_ORDER);
        //entity.setIsActive(64);
        entity.setLoginOutAlarm(false);
        JLog.d(TAG, "脚环" + id + " 恢复");
//        try {
//            this.mWriteStream.write(getSendStrByFootRingEntity(entity));
//        } catch (IOException e) {
//            e.printStackTrace();
//            JLog.d(TAG, "脚环:" + id + "休眠失败。");
//        }
    }

    /**
     * 查找脚环
     *
     * @param id
     * @return
     */
    public FootRingNewEntity findEntityFromList(String id) {

        CopyOnWriteArrayList<FootRingNewEntity> list = mRingList;
        if (list.size() == 1) {
            return list.get(0);
        }
        Iterator<FootRingNewEntity> iterator = list.iterator();
        FootRingNewEntity entity = null;
        while (iterator.hasNext()) {
            entity = iterator.next();
            if (id.equals(entity.getRingID())) {
                break;
            }
        }
        return entity;

    }

    /**
     * 传入经纬度。
     *
     * @param latitude  纬度。
     * @param longitude 经度。
     */
    public void setLocationLatLng(double latitude, double longitude) {
        if (mUploadModel == null) {
            mUploadModel = new TagCoordinateModel(latitude, longitude);
            mUploadModel.setTagId(SPUtil.getStringValue(SPUtil.PHONE_NAME));
            mUploadModel.setCode(SPUtil.getStringValue(SPUtil.LOGIN_CODE));
        }
        mUploadModel.setCoordinateY(latitude);
        mUploadModel.setCoordinateX(longitude);
    }

    /**
     * 上传脚环数据到服务器
     */
    public void refreshRingList() {
        CopyOnWriteArrayList<FootRingNewEntity> list = mRingList;
        if (mUploadRunnable == null || list == null || list.isEmpty()) {
            return;
        }
        if (mUploadModel == null) {
            mUploadModel = new TagCoordinateModel();
            mUploadModel.setTagId(SPUtil.getStringValue(SPUtil.PHONE_NAME));
            mUploadModel.setCode(SPUtil.getStringValue(SPUtil.LOGIN_CODE));
        }

        //List<ChildTagGroupModel> childList = mUploadModel.getListChildTag();
        List<ChildTagGroupModel> childList = new ArrayList<>();
        FootRingNewEntity entity = null;
        ChildTagGroupModel model = null;
        Iterator<FootRingNewEntity> iterator = list.iterator();

//        while (iterator.hasNext()) {
//            entity = iterator.next();
//            if (childList == null) {
//                childList = new ArrayList<>();
//                model = new ChildTagGroupModel();
//                copyEntityToModel(entity, model);
//                childList.add(model);
//                mUploadModel.setListChildTag(childList);
//            } else {
//                for (ChildTagGroupModel child : childList) {
//                    if (entity.getRingID().equals(child.getTagId())) {
//                        copyEntityToModel(entity, child);
//                    }
//                }
//            }
//        }
        while (iterator.hasNext()) {
            entity = iterator.next();
            if (!entity.isWithdraw()) {
                model = new ChildTagGroupModel();
                copyEntityToModel(entity, model);
                childList.add(model);
            }
        }
        mUploadModel.setListChildTag(childList);

        mUploadRunnable.setUploadByteArray(ObjectToByteArray.getUploadByte(mUploadModel, HttpConstant.NORMAL_ORDER_BYTE));
        synchronized (mLock) {
            mLock.notify();
        }
    }

    private void copyEntityToModel(FootRingNewEntity entity, ChildTagGroupModel model) {
        if (FootRingStatus.ESCAPE == entity.getStatus()) {
            model.setControl(2);
            model.setDistance(-1f);
            model.setSetDistance(entity.getSetRingDistance());
            model.setTagId(entity.getRingID());
            //model.setElectricityType(entity.getRingPower());
        } else if (FootRingStatus.NODATA == entity.getStatus()) {
            model.setControl(-1);
            model.setDistance(-1f);
            model.setSetDistance(entity.getSetRingDistance());
            model.setTagId(entity.getRingID());
        } else {
            model.setDistance(entity.getActualRingDistance());
            model.setSetDistance(entity.getSetRingDistance());
            model.setTagId(entity.getRingID());
            model.setElectricityType(entity.getRingPower());
            model.setLockType(entity.getLockType());
            model.setBroken(entity.getBrokenType());
            model.setControl(1);
        }
    }

    public void resetOrder2Server(String id) {
        mUploadRunnable.setUploadByteArray(ObjectToByteArray.getCloseAlarmByteArr(id, HttpConstant.RESET_ORDER_BYTE));
        synchronized (mLock) {
            mLock.notify();
        }
    }

    public void startMission(String id) {
        mUploadRunnable.setUploadByteArray(ObjectToByteArray.getCloseAlarmByteArr(id, HttpConstant.START_MISSION));
        synchronized (mLock) {
            mLock.notify();
        }
    }

    /**
     * 关闭警报
     *
     * @param ringID
     */
    public void closeAlarmOrder2Server(String ringID) {
        if (TextUtils.isEmpty(SPUtil.getStringValue(SPUtil.MISSION_ID))) {
            return;
        }
        if (mUploadRunnable == null) {
            return;
        }
        StringBuilder builder = new StringBuilder();
        builder.append(SPUtil.getStringValue(SPUtil.PHONE_NAME) + "&");
        builder.append(ringID);
        mUploadRunnable.setUploadByteArray(ObjectToByteArray.getCloseAlarmByteArr(builder.toString(), HttpConstant.CLOSE_ORDER_BYTE));
        synchronized (mLock) {
            mLock.notify();
        }
    }

    /**
     * 紧急报警。
     */
    public void emergencyAlarm2Server() {
        byte[] buff = ObjectToByteArray.getUploadByte(this.mUploadModel, HttpConstant.WARNING_ORDER_BYTE);
        WorkExecutePool.execute(new EmergencyRunnable(buff));
    }

    /**
     * 请求结束任务。
     */
    public void finishMiss2Server() {
        byte[] buff = ObjectToByteArray.getUploadByte(this.mUploadModel, HttpConstant.FINISH_ORDER_BYTE);
        mFinMissRunnable = new FinMissRunnable(buff);
        WorkExecutePool.execute(mFinMissRunnable);
    }


//    /**
//     * 请求清除弹框。
//     */
//    public void closeAlert2Server() {
//        byte[] buff = ObjectToByteArray.getUploadByte(this.mUploadModel, HttpConstant.CLEAR_ALERT_BYTE);
//        mFinMissRunnable =new FinMissRunnable(buff);
//        WorkExecutePool.execute(mFinMissRunnable);
//    }

    /**
     * 请求暂停
     */
    public void pauseMiss2Server() {
        byte[] buff = ObjectToByteArray.getUploadByte(this.mUploadModel, HttpConstant.PAUSE_ORDER_BYTE);
        mFinMissRunnable = new FinMissRunnable(buff);
        WorkExecutePool.execute(mFinMissRunnable);
    }

    /**
     * 请求恢复
     */
    public void resumeMiss2Server() {
        byte[] buff = ObjectToByteArray.getUploadByte(this.mUploadModel, HttpConstant.RESUME_ORDER_BYTE);
        mFinMissRunnable = new FinMissRunnable(buff);
        WorkExecutePool.execute(mFinMissRunnable);
    }

    public void destroyFinishThread() {
        if (mFinMissRunnable != null) {
            mFinMissRunnable.destroy();
            mFinMissRunnable = null;
        }
    }

    public void remindRingGPSLost() {
        VoiceImpl impl = VoiceImpl.getInstance(mAppContext);
        impl.playHighPriority(R.raw.warning_ring_gps_lost);
    }

    /**
     * 关闭串口和读取线程和上传线程
     */
    public void closeSerialPort() {
        if (mReadRunnable != null) {
            mReadRunnable.destroy();
            mReadRunnable = null;
        }
        if (mWorkPool != null) {
            mWorkPool.shutdown();
            mWorkPool = null;
        }
        if (mUploadRunnable != null) {
            mUploadRunnable.destroy();
            mUploadRunnable = null;
        }
        if (mSendRunnable != null) {
            //mSendRunnable.isRunning=false;
            mSendRunnable.destroy();
            mSendRunnable = null;

        }
        mBindedRingList = new ArrayList<>();
        //mRingList=null;
        mConnectRemind = null;
        resetVariables();
        try {
            if (mReadStream != null) {
                mReadStream.close();
                mWriteStream.close();
                mReadStream = null;
                mWriteStream = null;
            }
            if (mSerialPort != null) {
                mSerialPort.closeSerial(PORT);
                JLog.d(TAG, "SerialPort close success");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void resetVariables() {
        if (mRingList != null && !mRingList.isEmpty()) {
            mRingList.clear();
        }
        mUploadModel = null;
        this.mOrderSequence = 0;
        this.mRingList.clear();
    }

    public boolean isOpen() {
        return mReadStream != null;
    }

    public void power_Off() {
        if (mSerialPort != null) {
            mSerialPort.close(PORT);
            mSerialPort.rfid_poweroff();
            mSerialPort = null;
            JLog.d(TAG, " task removed rfid_poweroff.");
        }
    }
}